{% extends 'index.html' %}
{% block ace-content %}
<link href="https://cdn.bootcss.com/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.js"></script>
{% endblock %}
{% block page-content %}
<div id="page-wrapper">
    <div class="row">
         <div class="col-lg-12">
              <h1 class="page-header"><i class="fa fa-gears"></i><code>Ansible</code>剧本管理</h1>
         </div>
                <!-- /.col-lg-12 -->
    </div>
	<div class="row">
		<div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <i class="fa    fa-gears"></i>剧本执行
                        </div>
                        <!-- /.panel-heading -->
                        <div class="panel-body">
                            <!-- Nav tabs -->
                            <ul class="nav nav-tabs">
                                <li class="active"><a href="#home" data-toggle="tab"><i class="fa fa-rocket  "></i>执行页面</a>
                                </li>
                                <li><a href="#profile" data-toggle="tab"><i class="fa fa-bar-chart-o"></i>汇总展示</a>
                                </li>
                            </ul>

                            <!-- Tab panes -->
                            <div class="tab-content">
                                <div class="tab-pane fade in active" id="home">
                                	<br>
                                	<br>
									<div class="row">
			                                <div class="col-lg-4">
			                                <legend><i class="fa  fa-paper-plane"></i>Ansible服务器</legend>
			                                    <form role="form" id="ansiblePlayBookRun" class="main form-horizontal" >{% csrf_token %}
														<div class="form-group">
															 <label class="col-sm-2 control-label">剧本名称</label>
															 <div class="col-sm-10">											
																<input  type="text"   class="form-control" placeholder="输入模块"  value="{{playbook.playbook_name}}" disabled>
																<input  type="hidden"   class="form-control" name="ans_uuid" value="{{playbook.playbook_uuid}}">
															</div>
														</div> 																								
														<div class="form-group">
															{% if playbook.playbook_server_model == 'inventory' %}
																<label class="col-sm-2 control-label">动态主机组</label>
																<div class="col-sm-10"> 
<!-- 																	<button type="button"  class="btn btn-default" data-toggle="modal" data-target="#myInventoryModal" onclick="getAnsiblePlayBookInventory(this,{{playbook.playbook_server_value}})"><i class="fa  fa-eye  "></i></button> -->
																	<textarea class="form-control" rows="10" name="playbook_inventory" id="playbook_inventory" disabled></textarea>
															{% else %}
															 <label class="col-sm-2 control-label">服务器选择</label>
															 <div class="col-sm-10"> 
					                                            	{% if numberList %}
					                                            		<select multiple class="selectpicker" data-live-search="true" name="playbook_server"  disabled>
					                                            		{% for ds in numberList %}
					                                            			<option name="playbook_server" selected="selected" value="{{ds.playbook_server}}">{{ds.playbook_server}}</option>
					                                            		{% endfor %}
					                                            		</select>
					                                            	{% endif %}
					                                            	{% if serverList %}
<!-- 					                                            		<select multiple class="selectpicker" data-live-search="true" name="playbook_server" id="ansible_server"  required> -->
					                                            		<select multiple data-live-search="true" name="playbook_server" id="ansible_server"  required>
						                                            	{% for ds in serverList %}
						                                            		<option name="playbook_server" value="{{ds.ip}}">{{ds.ip}} | {{ds.project}} | {{ds.service}}</option>
						                                            	{% endfor %}
						                                            	</select>
					                                            	{% endif %}
					                                         {% endif %}  	
					                                            <input  type="hidden"   class="form-control"  name="playbook_uuid" value="{{playbook.playbook_uuid}}">
					                                            <input  type="hidden"   class="form-control"  name="model" value="playbook">
															 </div>
														</div>
														<div class="form-group">
															 <label class="col-sm-2 control-label">剧本文件</label>
															 <div class="col-sm-10">											
																<button type="button"  class="btn btn-default" data-toggle="modal" data-target="#myModal" onclick="getAnsiblePlayBookFile(this,{{playbook.id}})"><i class="fa  fa-eye  "></i></button>
															</div>
														</div> 			
														<div id="custom_model" class="form-group">
															 <label class="col-sm-2 control-label">剧本外部变量</label>
															 <div class="col-sm-10">	
															   	{% if playbook.playbook_vars %}										
																	<textarea class="form-control" rows="5" name="playbook_vars" id="playbook_vars" disabled>{{playbook.playbook_vars}}</textarea>
																{% else %}
																	<textarea class="form-control" rows="5" name="playbook_vars" id="playbook_vars"></textarea>
																{% endif %}
															</div>
														</div> 											
														<div class="form-group">
															 <label class="col-sm-2 control-label">Debug</label>
															 <div class="col-sm-10">										
																	<select class="form-control" name="ansible_debug">
																		<option value="off" name="ansible_model">关闭</option>	
																		<option value="on" name="ansible_model">开启</option> 	
																	</select>
															</div>
														</div> 																																																				 											
														<legend></legend>
														<div class="form-group">
															<label class="col-sm-3 control-label"></label>
															<button type="button"  onclick="repealFromVaule(this)" class="btn btn-default" >撤销</button>
													 		<button type="button"  class="btn btn-default" onclick="runAnsiblePlayBook(this)" >执行</button>
												 		</div>									 		
													</form>                                        
			                                </div>
			                                <!-- /.col-lg-6 (nested) -->
			                                <div class="col-lg-8">
			                                    <legend><i class="fa  fa-paper-plane-o"></i>执行结果</legend>
												<pre>
							                        <div id="result">
							                        </div>
							                    </pre>                                      
			                                <!-- /.col-lg-6 (nested) -->
			                            </div>
	                            </div>
                            </div>
                            <div class="tab-pane fade" id="profile">
                            	<br>
                            	<br>
	                            <div class="row">
					                <div class="col-lg-6">
					                    <div class="panel panel-default">
					                        <div class="panel-heading">
					                            	<i class="fa fa-sitemap  "></i>状态比率
					                        </div>
					                        <!-- /.panel-heading -->
					                        <div class="panel-body">
					                            <div class="table-responsive">
													<div id="statPer" style="width: 600px;height:400px;">
													</div>
					                            </div>
					                            <!-- /.table-responsive -->
					                        </div>
					                        <!-- /.panel-body -->
					                    </div>
					                    <!-- /.panel -->
					                </div>	                            
					                <div class="col-lg-6">
					                    <div class="panel panel-info">
					                        <div class="panel-heading">
					                            	<i class="fa fa-tachometer"></i>事件汇总 
					                        </div>
					                        <!-- /.panel-heading -->
					                        <div class="panel-body">
					                            <div class="table-responsive">
													<div id="summary">
													</div>
					                            </div>
					                            <!-- /.table-responsive -->
					                        </div>
					                        <!-- /.panel-body -->
					                    </div>
					                    <!-- /.panel -->
					                </div>
                            	</div> 
                            </div>                           
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>	
    </div>
</div>

<div class="modal fade" id="myInventoryModal" tabindex="-1" role="dialog" aria-labelledby="myInventoryModalLabel" aria-hidden="true">
	<div class="modal-dialog" style="width:1280px;height:auto;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myInventoryModalLabel">
					动态资产组
				</h4>
			</div>
			<div class="modal-body">
				<pre>
					<div id="play_inventory_content">
					</div>
				</pre>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">关闭
				</button>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>


<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog" style="width:1280px;height:auto;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myModalLabel">
					剧本文件内容
				</h4>
			</div>
			<div class="modal-body">
				<pre>
					<div id="play_content">
					</div>
				</pre>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">关闭
				</button>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>

<div style="visibility:hidden"><a id="scrollToTop"></a></div>
<script type="text/javascript">	
	{% if playbook.playbook_vars %}
		var songResJson=JSON.parse(document.getElementById('playbook_vars').value);
		$("#playbook_vars").text(JSON.stringify(songResJson,null,2)); 
	{% endif %}
	

	$(document).ready(function(){ 

			$.ajax({
					url:'/api/inventory/'+ {{playbook.playbook_server_value}} +'/', //请求地址
					type:"GET",  //提交类似
				    processData: false,
				    contentType: false,				
					success:function(response){
						if (response["code"] == 200){
							$("#playbook_inventory").text(JSON.stringify(response["data"],null,2)); 	
						}						
					}
	
				});			
	})	
	
    $(document).ready(function() {
        $('#ansible_server').multiselect({
            enableClickableOptGroups: true,
            enableCollapsibleOptGroups: true,
            includeSelectAllOption: true,
           	enableFiltering: true,            
        });
    });
    

	function getAnsiblePlayBookInventory(obj,id) {
		var btnObj = $(obj);
		$.ajax({
			url:'/api/inventory/'+id+'/', //请求地址
			type:"GET",  //提交类似
			data:{
				"id":id
			},  //提交参数
			success:function(response){
				btnObj.removeAttr('disabled');
				if (response["code"] == "200"){
					btnObj.removeAttr('disabled');
					$("#play_inventory_content").html( JSON.stringify(response["data"],null,4)); 
				}
				
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm("查看失败", window.wxc.xcConfirm.typeEnum.error);
	    	}
		})
	}    
	
	function getAnsiblePlayBookFile(obj,id) {
		var btnObj = $(obj);
		$.ajax({
			url:'/apps/playbook/file/'+id+'/', //请求地址
			type:"POST",  //提交类似
			data:{
				"id":id
			},  //提交参数
			success:function(response){
				btnObj.removeAttr('disabled');
				if (response["code"] == "200"){
					btnObj.removeAttr('disabled');
					$("#play_content").html(response["data"]); 
				}
				
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm("查看失败", window.wxc.xcConfirm.typeEnum.error);
	    	}
		})
	}
		
    
	function runAnsiblePlayBook(obj) {
		var btnObj = $(obj);
		btnObj.attr('disabled',true);
		var form = document.getElementById('ansiblePlayBookRun');
		var post_data = {};
		for (var i = 1; i < form.length; ++i) {
			var name = form[i].name;
			var value = form[i].value;
			var project = name.indexOf("playbook_server");
			if ( project==0 && value.length==0 ){
				window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
				btnObj.removeAttr('disabled');
				return false;
			}
		};
		$("#result").html("服务器正在处理，请稍等。。。");
		/* 轮训获取结果 开始  */
	   var interval = setInterval(function(){  
	        $.ajax({  
	            url : '/apps/run/',  
	            type : 'post', 
	            data:$('#ansiblePlayBookRun').serialize(),
	            success : function(result){
	            	if (result["msg"] !== null ){
	            		$("#result").append("<p>"+result["msg"]+"</p>");
	            		document.getElementById("scrollToTop").scrollIntoView(); 
	            		if (result["msg"].indexOf("[Done]") == 0){            			
	            			clearInterval(interval);
	            			window.wxc.xcConfirm("Ansible执行完成", window.wxc.xcConfirm.typeEnum.success);
	            			btnObj.removeAttr('disabled');
	            		}
	            	}
	            },
		    	error:function(response){
		    		btnObj.removeAttr('disabled');
		    		clearInterval(interval);
		    	}	            
	        });  
	    },1000); 
// 	   document.getElementById("ans_uuid").value = uuid();
// 	    /* 轮训获取结果结束  */
		$.ajax({
			url:'/apps/playbook/run/'+ {{playbook.id}} +'/', //请求地址
			type:"POST",  //提交类似
			data:$('#ansiblePlayBookRun').serialize(),  //提交参数
			success:function(response){
				btnObj.removeAttr('disabled');
				if (response["code"] == "500"){
					clearInterval(interval);
					btnObj.removeAttr('disabled');
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				}
				else if(response["code"] == "200"){
        			var htmlStr = '<table class="table"><thead><th>主机</th><th>成功</th><th>失败</th><th>跳过</th><th>更改</th><th>主机不可达</th><th>结果</th></thead><tbody>';
        			for (x in response["data"]){
        				if (response["data"][x]['result'] == 'Succeed'){
        					var btTag = '<button type="button" class="btn btn-outline btn-success disabled">成功</button>'
        				}
        				else{
        					var btTag = '<button type="button" class="btn btn-outline btn-danger disabled">失败</button>'
        				};
						htmlStr += '<tr><td>'+ response["data"][x]['host'] +
						'</td><td><span class="label label-success">' + response["data"][x]['ok'] + '</span>' + 
						'</td><td><span class="label label-danger">' + response["data"][x]['failed'] + '</span>' +
						'</td><td><span class="label label-default">' + response["data"][x]['skipped'] + '</span>' +
						'</td><td><span class="label label-warning">' + response["data"][x]['changed'] + '</span>' +
						'</td><td><span class="label label-info">' + response["data"][x]['unreachable'] + '</span>' +
						'</td><td>' + btTag + '</tr>';																
					};
					htmlStr += '</tbody></table>'
					$('#summary').html(htmlStr);
					runAnsibleStatusPer(response["statPer"]);
				};
				
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm("运行失败", window.wxc.xcConfirm.typeEnum.error);
	    		clearInterval(interval);
	    	}
		})	
	}	

	var myChart = echarts.init(document.getElementById('statPer'));
	function runAnsibleStatusPer(statPer) {
	    option = {
	    	    title : {
	    	        text: '剧本部署状态比率',
	    	        subtext: 'Task Status',
	    	        x:'center'
	    	    },
	    	    tooltip : {
	    	        trigger: 'item',
	    	        formatter: "{a} <br/>{b} : {c} ({d}%)"
	    	    },
	    	    legend: {
	    	        orient : 'vertical',
	    	        x : 'left',
	    	        data:['成功','失败','更改','跳过','主机不可达']
	    	    },
	    	    toolbox: {
	    	        show : true,
	    	        feature : {
	    	            mark : {show: true},
	    	            dataView : {show: true, readOnly: false},
	    	            magicType : {
	    	                show: true, 
	    	                type: ['pie', 'funnel'],
	    	                option: {
	    	                    funnel: {
	    	                        x: '25%',
	    	                        width: '50%',
	    	                        funnelAlign: 'left',
	    	                        max: 1548
	    	                    }
	    	                }
	    	            },
	    	            restore : {show: true},
	    	            saveAsImage : {show: true}
	    	        }
	    	    },
	    	    calculable : true,
	    	    series : [
	    	        {
	    	            name:'Task Status Per',
	    	            type:'pie',
	    	            radius : '55%',
	    	            center: ['50%', '60%'],
	    	            data:[
	    	                {value:statPer["ok"], name:'成功'},
	    	                {value:statPer["failed"], name:'失败'},
	    	                {value:statPer["changed"], name:'更改'},
	    	                {value:statPer["skipped"], name:'跳过'},
	    	                {value:statPer["unreachable"], name:'主机不可达'}
	    	            ]
	    	        }
	    	    ]
	    	};
	    	                    
	 myChart.setOption(option);
	};

	
{% if errorInfo %}
	window.wxc.xcConfirm("{{errorInfo}}", window.wxc.xcConfirm.typeEnum.error);
{% endif %}
</script>

{% endblock %}